/*
 * Thread Demos
 * Spring 2013 TCSS 558
 * Daniel M. Zimmerman
 */

package threads;

/**
 * A class that demonstrates thread joins.
 * 
 * @author Daniel M. Zimmerman
 * @version Spring 2013
 */
public class Joinee implements Runnable
{
  // Static Fields
  
  /**
   * The number of lines to print to standard output.
   */
  public static final int NUMBER_OF_LINES = 5;
  
  // Instance Methods
  
  /**
   * Prints some lines to standard output, then exits.
   */
  public void run()
  {
    for (int i = 0; i < NUMBER_OF_LINES; i++)
    {
      System.out.println(Thread.currentThread() + " Line number " + i);
    }

    System.out.println(Thread.currentThread() + " Thread exiting.");
  }
  
  // Main Method
  
  /**
   * Creates a thread, then joins it.
   * 
   * @param the_args command line arguments, not used.
   */
  public static void main(final String[] the_args)
  {
    final Thread thread = new Thread(new Joinee());
    System.out.println(Thread.currentThread() + " Starting thread.");
    thread.start();
    
    while (thread.isAlive())
    {
      try
      {
        thread.join();
      }
      catch (final InterruptedException e)
      {
        // this should never happen
      
        System.err.println(Thread.currentThread() + " We were interrupted!");
      }
    }
    
    // we are absolutely sure that "thread" is dead.
    
    System.out.println(Thread.currentThread() + " Thread terminated.");
  }
}
